<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlinterp - An overview of the Perl interpreter - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlinterp">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlinterp.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlinterp">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlinterp">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlinterp">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlinterp">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlinterp">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlinterp">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlinterp">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlinterp">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlinterp">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlinterp">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlinterp">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlinterp">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlinterp">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlinterp">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlinterp">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlinterp">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlinterp">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlinterp">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlinterp">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlinterp">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlinterp">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlinterp">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlinterp">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlinterp">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlinterp">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlinterp">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlinterp">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlinterp">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlinterp">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlinterp">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlinterp">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlinterp">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlinterp">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlinterp">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlinterp">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlinterp">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlinterp">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlinterp">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlinterp">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlinterp">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlinterp">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlinterp">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlinterp">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlinterp">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlinterp">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlinterp">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlinterp">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlinterp">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlinterp">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlinterp">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlinterp">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlinterp">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlinterp">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlinterp">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlinterp">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlinterp">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlinterp">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlinterp">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlinterp">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlinterp">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlinterp">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlinterp">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlinterp">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlinterp">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlinterp">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlinterp">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlinterp">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlinterp">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlinterp">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlinterp">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlinterp">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlinterp">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlinterp">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlinterp">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlinterp">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlinterp">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlinterp">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlinterp">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlinterp">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlinterp">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlinterp.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlinterp">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlinterp">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlinterp">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlinterp">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlinterp">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlinterp">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlinterp">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlinterp">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlinterp">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlinterp">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlinterp">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlinterp">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlinterp">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlinterp">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlinterp">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlinterp">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlinterp">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlinterp">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlinterp">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlinterp">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlinterp">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlinterp">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlinterp">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlinterp">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlinterp">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlinterp">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlinterp">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlinterp">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlinterp">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlinterp">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlinterp">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlinterp">5.35.1</a>
          <a class="dropdown-item active" href="perlinterp.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlinterp.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlinterp.html">perlinterp</a>
          <div id="more">
            (<a href="perlinterp.txt">source</a>,
            <a href="https://metacpan.org/pod/perlinterp">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#NAME">NAME</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#DESCRIPTION">DESCRIPTION</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#ELEMENTS-OF-THE-INTERPRETER">ELEMENTS OF THE INTERPRETER</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#Startup">Startup</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#Parsing">Parsing</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#Optimization">Optimization</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#Running">Running</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#Exception-handing">Exception handing</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#INTERNAL-VARIABLE-TYPES">INTERNAL VARIABLE TYPES</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#OP-TREES">OP TREES</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#STACKS">STACKS</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#Argument-stack">Argument stack</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#Mark-stack">Mark stack</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#Save-stack">Save stack</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#MILLIONS-OF-MACROS">MILLIONS OF MACROS</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlinterp.html#FURTHER-READING">FURTHER READING</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlinterp.html#NAME">#</a>NAME</h1>

<p>perlinterp - An overview of the Perl interpreter</p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlinterp.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>This document provides an overview of how the Perl interpreter works at the level of C code, along with pointers to the relevant C source code files.</p>

<h1 id="ELEMENTS-OF-THE-INTERPRETER"><a class="permalink" href="perlinterp.html#ELEMENTS-OF-THE-INTERPRETER">#</a><a id="ELEMENTS"></a>ELEMENTS OF THE INTERPRETER</h1>

<p>The work of the interpreter has two main stages: compiling the code into the internal representation, or bytecode, and then executing it. <a href="perlguts.html#Compiled-code">&quot;Compiled code&quot; in perlguts</a> explains exactly how the compilation stage happens.</p>

<p>Here is a short breakdown of perl&#39;s operation:</p>

<h2 id="Startup"><a class="permalink" href="perlinterp.html#Startup">#</a>Startup</h2>

<p>The action begins in <i>perlmain.c</i>. (or <i>miniperlmain.c</i> for miniperl) This is very high-level code, enough to fit on a single screen, and it resembles the code found in <a href="perlembed.html">perlembed</a>; most of the real action takes place in <i>perl.c</i></p>

<p><i>perlmain.c</i> is generated by <code>ExtUtils::Miniperl</code> from <i>miniperlmain.c</i> at make time, so you should make perl to follow this along.</p>

<p>First, <i>perlmain.c</i> allocates some memory and constructs a Perl interpreter, along these lines:</p>

<pre><code>1 PERL_SYS_INIT3(&amp;argc,&amp;argv,&amp;env);
2
3 if (!PL_do_undump) {
4     my_perl = perl_alloc();
5     if (!my_perl)
6         exit(1);
7     perl_construct(my_perl);
8     PL_perl_destruct_level = 0;
9 }</code></pre>

<p>Line 1 is a macro, and its definition is dependent on your operating system. Line 3 references <code>PL_do_undump</code>, a global variable - all global variables in Perl start with <code>PL_</code>. This tells you whether the current running program was created with the <code>-u</code> flag to perl and then <i>undump</i>, which means it&#39;s going to be false in any sane context.</p>

<p>Line 4 calls a function in <i>perl.c</i> to allocate memory for a Perl interpreter. It&#39;s quite a simple function, and the guts of it looks like this:</p>

<pre><code>my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));</code></pre>

<p>Here you see an example of Perl&#39;s system abstraction, which we&#39;ll see later: <code>PerlMem_malloc</code> is either your system&#39;s <code>malloc</code>, or Perl&#39;s own <code>malloc</code> as defined in <i>malloc.c</i> if you selected that option at configure time.</p>

<p>Next, in line 7, we construct the interpreter using perl_construct, also in <i>perl.c</i>; this sets up all the special variables that Perl needs, the stacks, and so on.</p>

<p>Now we pass Perl the command line options, and tell it to go:</p>

<pre><code>if (!perl_parse(my_perl, xs_init, argc, argv, (char **)NULL))
    perl_run(my_perl);

exitstatus = perl_destruct(my_perl);

perl_free(my_perl);</code></pre>

<p><code>perl_parse</code> is actually a wrapper around <code>S_parse_body</code>, as defined in <i>perl.c</i>, which processes the command line options, sets up any statically linked XS modules, opens the program and calls <code>yyparse</code> to parse it.</p>

<h2 id="Parsing"><a class="permalink" href="perlinterp.html#Parsing">#</a>Parsing</h2>

<p>The aim of this stage is to take the Perl source, and turn it into an op tree. We&#39;ll see what one of those looks like later. Strictly speaking, there&#39;s three things going on here.</p>

<p><code>yyparse</code>, the parser, lives in <i>perly.c</i>, although you&#39;re better off reading the original YACC input in <i>perly.y</i>. (Yes, Virginia, there <b>is</b> a YACC grammar for Perl!) The job of the parser is to take your code and &quot;understand&quot; it, splitting it into sentences, deciding which operands go with which operators and so on.</p>

<p>The parser is nobly assisted by the lexer, which chunks up your input into tokens, and decides what type of thing each token is: a variable name, an operator, a bareword, a subroutine, a core function, and so on. The main point of entry to the lexer is <code>yylex</code>, and that and its associated routines can be found in <i>toke.c</i>. Perl isn&#39;t much like other computer languages; it&#39;s highly context sensitive at times, it can be tricky to work out what sort of token something is, or where a token ends. As such, there&#39;s a lot of interplay between the tokeniser and the parser, which can get pretty frightening if you&#39;re not used to it.</p>

<p>As the parser understands a Perl program, it builds up a tree of operations for the interpreter to perform during execution. The routines which construct and link together the various operations are to be found in <i>op.c</i>, and will be examined later.</p>

<h2 id="Optimization"><a class="permalink" href="perlinterp.html#Optimization">#</a>Optimization</h2>

<p>Now the parsing stage is complete, and the finished tree represents the operations that the Perl interpreter needs to perform to execute our program. Next, Perl does a dry run over the tree looking for optimisations: constant expressions such as <code>3 + 4</code> will be computed now, and the optimizer will also see if any multiple operations can be replaced with a single one. For instance, to fetch the variable <code>$foo</code>, instead of grabbing the glob <code>*foo</code> and looking at the scalar component, the optimizer fiddles the op tree to use a function which directly looks up the scalar in question. The main optimizer is <code>peep</code> in <i>op.c</i>, and many ops have their own optimizing functions.</p>

<h2 id="Running"><a class="permalink" href="perlinterp.html#Running">#</a>Running</h2>

<p>Now we&#39;re finally ready to go: we have compiled Perl byte code, and all that&#39;s left to do is run it. The actual execution is done by the <code>runops_standard</code> function in <i>run.c</i>; more specifically, it&#39;s done by these three innocent looking lines:</p>

<pre><code>while ((PL_op = PL_op-&gt;op_ppaddr(aTHX))) {
    PERL_ASYNC_CHECK();
}</code></pre>

<p>You may be more comfortable with the Perl version of that:</p>

<pre><code>PERL_ASYNC_CHECK() while $Perl::op = &amp;{$Perl::op-&gt;{function}};</code></pre>

<p>Well, maybe not. Anyway, each op contains a function pointer, which stipulates the function which will actually carry out the operation. This function will return the next op in the sequence - this allows for things like <code>if</code> which choose the next op dynamically at run time. The <code>PERL_ASYNC_CHECK</code> makes sure that things like signals interrupt execution if required.</p>

<p>The actual functions called are known as PP code, and they&#39;re spread between four files: <i>pp_hot.c</i> contains the &quot;hot&quot; code, which is most often used and highly optimized, <i>pp_sys.c</i> contains all the system-specific functions, <i>pp_ctl.c</i> contains the functions which implement control structures (<code>if</code>, <code>while</code> and the like) and <i>pp.c</i> contains everything else. These are, if you like, the C code for Perl&#39;s built-in functions and operators.</p>

<p>Note that each <code>pp_</code> function is expected to return a pointer to the next op. Calls to perl subs (and eval blocks) are handled within the same runops loop, and do not consume extra space on the C stack. For example, <code>pp_entersub</code> and <code>pp_entertry</code> just push a <code>CxSUB</code> or <code>CxEVAL</code> block struct onto the context stack which contain the address of the op following the sub call or eval. They then return the first op of that sub or eval block, and so execution continues of that sub or block. Later, a <code>pp_leavesub</code> or <code>pp_leavetry</code> op pops the <code>CxSUB</code> or <code>CxEVAL</code>, retrieves the return op from it, and returns it.</p>

<h2 id="Exception-handing"><a class="permalink" href="perlinterp.html#Exception-handing">#</a><a id="Exception"></a>Exception handing</h2>

<p>Perl&#39;s exception handing (i.e. <code>die</code> etc.) is built on top of the low-level <code>setjmp()</code>/<code>longjmp()</code> C-library functions. These basically provide a way to capture the current PC and SP registers and later restore them; i.e. a <code>longjmp()</code> continues at the point in code where a previous <code>setjmp()</code> was done, with anything further up on the C stack being lost. This is why code should always save values using <code>SAVE_<i>FOO</i></code> rather than in auto variables.</p>

<p>The perl core wraps <code>setjmp()</code> etc in the macros <code>JMPENV_PUSH</code> and <code>JMPENV_JUMP</code>. The basic rule of perl exceptions is that <code>exit</code>, and <code>die</code> (in the absence of <code>eval</code>) perform a <code>JMPENV_JUMP(2)</code>, while <code>die</code> within <code>eval</code> does a <code>JMPENV_JUMP(3)</code>.</p>

<p>At entry points to perl, such as <code>perl_parse()</code>, <code>perl_run()</code> and <code>call_sv(cv, G_EVAL)</code> each does a <code>JMPENV_PUSH</code>, then enter a runops loop or whatever, and handle possible exception returns. For a 2 return, final cleanup is performed, such as popping stacks and calling <code>CHECK</code> or <code>END</code> blocks. Amongst other things, this is how scope cleanup still occurs during an <code>exit</code>.</p>

<p>If a <code>die</code> can find a <code>CxEVAL</code> block on the context stack, then the stack is popped to that level and the return op in that block is assigned to <code>PL_restartop</code>; then a <code>JMPENV_JUMP(3)</code> is performed. This normally passes control back to the guard. In the case of <code>perl_run</code> and <code>call_sv</code>, a non-null <code>PL_restartop</code> triggers re-entry to the runops loop. The is the normal way that <code>die</code> or <code>croak</code> is handled within an <code>eval</code>.</p>

<p>Sometimes ops are executed within an inner runops loop, such as tie, sort or overload code. In this case, something like</p>

<pre><code class="plaintext">sub FETCH { eval { die } }</code></pre>

<p>would cause a longjmp right back to the guard in <code>perl_run</code>, popping both runops loops, which is clearly incorrect. One way to avoid this is for the tie code to do a <code>JMPENV_PUSH</code> before executing <code>FETCH</code> in the inner runops loop, but for efficiency reasons, perl in fact just sets a flag, using <code>CATCH_SET(TRUE)</code>. The <code>pp_require</code>, <code>pp_entereval</code> and <code>pp_entertry</code> ops check this flag, and if true, they call <code>docatch</code>, which does a <code>JMPENV_PUSH</code> and starts a new runops level to execute the code, rather than doing it on the current loop.</p>

<p>As a further optimisation, on exit from the eval block in the <code>FETCH</code>, execution of the code following the block is still carried on in the inner loop. When an exception is raised, <code>docatch</code> compares the <code>JMPENV</code> level of the <code>CxEVAL</code> with <code>PL_top_env</code> and if they differ, just re-throws the exception. In this way any inner loops get popped.</p>

<p>Here&#39;s an example.</p>

<pre><code>1: eval { tie @a, &#39;A&#39; };
2: sub A::TIEARRAY {
3:     eval { die };
4:     die;
5: }</code></pre>

<p>To run this code, <code>perl_run</code> is called, which does a <code>JMPENV_PUSH</code> then enters a runops loop. This loop executes the eval and tie ops on line 1, with the eval pushing a <code>CxEVAL</code> onto the context stack.</p>

<p>The <code>pp_tie</code> does a <code>CATCH_SET(TRUE)</code>, then starts a second runops loop to execute the body of <code>TIEARRAY</code>. When it executes the entertry op on line 3, <code>CATCH_GET</code> is true, so <code>pp_entertry</code> calls <code>docatch</code> which does a <code>JMPENV_PUSH</code> and starts a third runops loop, which then executes the die op. At this point the C call stack looks like this:</p>

<pre><code class="plaintext">Perl_pp_die
Perl_runops      # third loop
S_docatch_body
S_docatch
Perl_pp_entertry
Perl_runops      # second loop
S_call_body
Perl_call_sv
Perl_pp_tie
Perl_runops      # first loop
S_run_body
perl_run
main</code></pre>

<p>and the context and data stacks, as shown by <code>-Dstv</code>, look like:</p>

<pre><code class="plaintext">STACK 0: MAIN
  CX 0: BLOCK  =&gt;
  CX 1: EVAL   =&gt; AV()  PV(&quot;A&quot;\0)
  retop=leave
STACK 1: MAGIC
  CX 0: SUB    =&gt;
  retop=(null)
  CX 1: EVAL   =&gt; *
retop=nextstate</code></pre>

<p>The die pops the first <code>CxEVAL</code> off the context stack, sets <code>PL_restartop</code> from it, does a <code>JMPENV_JUMP(3)</code>, and control returns to the top <code>docatch</code>. This then starts another third-level runops level, which executes the nextstate, pushmark and die ops on line 4. At the point that the second <code>pp_die</code> is called, the C call stack looks exactly like that above, even though we are no longer within an inner eval; this is because of the optimization mentioned earlier. However, the context stack now looks like this, ie with the top CxEVAL popped:</p>

<pre><code class="plaintext">STACK 0: MAIN
  CX 0: BLOCK  =&gt;
  CX 1: EVAL   =&gt; AV()  PV(&quot;A&quot;\0)
  retop=leave
STACK 1: MAGIC
  CX 0: SUB    =&gt;
  retop=(null)</code></pre>

<p>The die on line 4 pops the context stack back down to the CxEVAL, leaving it as:</p>

<pre><code class="plaintext">STACK 0: MAIN
  CX 0: BLOCK  =&gt;</code></pre>

<p>As usual, <code>PL_restartop</code> is extracted from the <code>CxEVAL</code>, and a <code>JMPENV_JUMP(3)</code> done, which pops the C stack back to the docatch:</p>

<pre><code class="plaintext">S_docatch
Perl_pp_entertry
Perl_runops      # second loop
S_call_body
Perl_call_sv
Perl_pp_tie
Perl_runops      # first loop
S_run_body
perl_run
main</code></pre>

<p>In this case, because the <code>JMPENV</code> level recorded in the <code>CxEVAL</code> differs from the current one, <code>docatch</code> just does a <code>JMPENV_JUMP(3)</code> and the C stack unwinds to:</p>

<pre><code class="plaintext">perl_run
main</code></pre>

<p>Because <code>PL_restartop</code> is non-null, <code>run_body</code> starts a new runops loop and execution continues.</p>

<h2 id="INTERNAL-VARIABLE-TYPES"><a class="permalink" href="perlinterp.html#INTERNAL-VARIABLE-TYPES">#</a><a id="INTERNAL"></a>INTERNAL VARIABLE TYPES</h2>

<p>You should by now have had a look at <a href="perlguts.html">perlguts</a>, which tells you about Perl&#39;s internal variable types: SVs, HVs, AVs and the rest. If not, do that now.</p>

<p>These variables are used not only to represent Perl-space variables, but also any constants in the code, as well as some structures completely internal to Perl. The symbol table, for instance, is an ordinary Perl hash. Your code is represented by an SV as it&#39;s read into the parser; any program files you call are opened via ordinary Perl filehandles, and so on.</p>

<p>The core <a href="./Devel::Peek.html">Devel::Peek</a> module lets us examine SVs from a Perl program. Let&#39;s see, for instance, how Perl treats the constant <code>&quot;hello&quot;</code>.</p>

<pre><code class="plaintext">  % perl -MDevel::Peek -e &#39;Dump(&quot;hello&quot;)&#39;
1 SV = PV(0xa041450) at 0xa04ecbc
2   REFCNT = 1
3   FLAGS = (POK,READONLY,pPOK)
4   PV = 0xa0484e0 &quot;hello&quot;\0
5   CUR = 5
6   LEN = 6</code></pre>

<p>Reading <code>Devel::Peek</code> output takes a bit of practise, so let&#39;s go through it line by line.</p>

<p>Line 1 tells us we&#39;re looking at an SV which lives at <code>0xa04ecbc</code> in memory. SVs themselves are very simple structures, but they contain a pointer to a more complex structure. In this case, it&#39;s a PV, a structure which holds a string value, at location <code>0xa041450</code>. Line 2 is the reference count; there are no other references to this data, so it&#39;s 1.</p>

<p>Line 3 are the flags for this SV - it&#39;s OK to use it as a PV, it&#39;s a read-only SV (because it&#39;s a constant) and the data is a PV internally. Next we&#39;ve got the contents of the string, starting at location <code>0xa0484e0</code>.</p>

<p>Line 5 gives us the current length of the string - note that this does <b>not</b> include the null terminator. Line 6 is not the length of the string, but the length of the currently allocated buffer; as the string grows, Perl automatically extends the available storage via a routine called <code>SvGROW</code>.</p>

<p>You can get at any of these quantities from C very easily; just add <code>Sv</code> to the name of the field shown in the snippet, and you&#39;ve got a macro which will return the value: <code>SvCUR(sv)</code> returns the current length of the string, <code>SvREFCOUNT(sv)</code> returns the reference count, <code>SvPV(sv, len)</code> returns the string itself with its length, and so on. More macros to manipulate these properties can be found in <a href="perlguts.html">perlguts</a>.</p>

<p>Let&#39;s take an example of manipulating a PV, from <code>sv_catpvn</code>, in <i>sv.c</i></p>

<pre><code> 1  void
 2  Perl_sv_catpvn(pTHX_ SV *sv, const char *ptr, STRLEN len)
 3  {
 4      STRLEN tlen;
 5      char *junk;

 6      junk = SvPV_force(sv, tlen);
 7      SvGROW(sv, tlen + len + 1);
 8      if (ptr == junk)
 9          ptr = SvPVX(sv);
10      Move(ptr,SvPVX(sv)+tlen,len,char);
11      SvCUR(sv) += len;
12      *SvEND(sv) = &#39;\0&#39;;
13      (void)SvPOK_only_UTF8(sv);          /* validate pointer */
14      SvTAINT(sv);
15  }</code></pre>

<p>This is a function which adds a string, <code>ptr</code>, of length <code>len</code> onto the end of the PV stored in <code>sv</code>. The first thing we do in line 6 is make sure that the SV <b>has</b> a valid PV, by calling the <code>SvPV_force</code> macro to force a PV. As a side effect, <code>tlen</code> gets set to the current value of the PV, and the PV itself is returned to <code>junk</code>.</p>

<p>In line 7, we make sure that the SV will have enough room to accommodate the old string, the new string and the null terminator. If <code>LEN</code> isn&#39;t big enough, <code>SvGROW</code> will reallocate space for us.</p>

<p>Now, if <code>junk</code> is the same as the string we&#39;re trying to add, we can grab the string directly from the SV; <code>SvPVX</code> is the address of the PV in the SV.</p>

<p>Line 10 does the actual catenation: the <code>Move</code> macro moves a chunk of memory around: we move the string <code>ptr</code> to the end of the PV - that&#39;s the start of the PV plus its current length. We&#39;re moving <code>len</code> bytes of type <code>char</code>. After doing so, we need to tell Perl we&#39;ve extended the string, by altering <code>CUR</code> to reflect the new length. <code>SvEND</code> is a macro which gives us the end of the string, so that needs to be a <code>&quot;\0&quot;</code>.</p>

<p>Line 13 manipulates the flags; since we&#39;ve changed the PV, any IV or NV values will no longer be valid: if we have <code>$a=10; $a.=&quot;6&quot;;</code> we don&#39;t want to use the old IV of 10. <code>SvPOK_only_utf8</code> is a special UTF-8-aware version of <code>SvPOK_only</code>, a macro which turns off the IOK and NOK flags and turns on POK. The final <code>SvTAINT</code> is a macro which launders tainted data if taint mode is turned on.</p>

<p>AVs and HVs are more complicated, but SVs are by far the most common variable type being thrown around. Having seen something of how we manipulate these, let&#39;s go on and look at how the op tree is constructed.</p>

<h1 id="OP-TREES"><a class="permalink" href="perlinterp.html#OP-TREES">#</a><a id="OP"></a>OP TREES</h1>

<p>First, what is the op tree, anyway? The op tree is the parsed representation of your program, as we saw in our section on parsing, and it&#39;s the sequence of operations that Perl goes through to execute your program, as we saw in <a href="perlinterp.html#Running">&quot;Running&quot;</a>.</p>

<p>An op is a fundamental operation that Perl can perform: all the built-in functions and operators are ops, and there are a series of ops which deal with concepts the interpreter needs internally - entering and leaving a block, ending a statement, fetching a variable, and so on.</p>

<p>The op tree is connected in two ways: you can imagine that there are two &quot;routes&quot; through it, two orders in which you can traverse the tree. First, parse order reflects how the parser understood the code, and secondly, execution order tells perl what order to perform the operations in.</p>

<p>The easiest way to examine the op tree is to stop Perl after it has finished parsing, and get it to dump out the tree. This is exactly what the compiler backends <a href="./B::Terse.html">B::Terse</a>, <a href="./B::Concise.html">B::Concise</a> and CPAN module &lt;B::Debug do.</p>

<p>Let&#39;s have a look at how Perl sees <code>$a = $b + $c</code>:</p>

<pre><code> % perl -MO=Terse -e &#39;$a=$b+$c&#39;
 1  LISTOP (0x8179888) leave
 2      OP (0x81798b0) enter
 3      COP (0x8179850) nextstate
 4      BINOP (0x8179828) sassign
 5          BINOP (0x8179800) add [1]
 6              UNOP (0x81796e0) null [15]
 7                  SVOP (0x80fafe0) gvsv  GV (0x80fa4cc) *b
 8              UNOP (0x81797e0) null [15]
 9                  SVOP (0x8179700) gvsv  GV (0x80efeb0) *c
10          UNOP (0x816b4f0) null [15]
11              SVOP (0x816dcf0) gvsv  GV (0x80fa460) *a</code></pre>

<p>Let&#39;s start in the middle, at line 4. This is a BINOP, a binary operator, which is at location <code>0x8179828</code>. The specific operator in question is <code>sassign</code> - scalar assignment - and you can find the code which implements it in the function <code>pp_sassign</code> in <i>pp_hot.c</i>. As a binary operator, it has two children: the add operator, providing the result of <code>$b+$c</code>, is uppermost on line 5, and the left hand side is on line 10.</p>

<p>Line 10 is the null op: this does exactly nothing. What is that doing there? If you see the null op, it&#39;s a sign that something has been optimized away after parsing. As we mentioned in <a href="perlinterp.html#Optimization">&quot;Optimization&quot;</a>, the optimization stage sometimes converts two operations into one, for example when fetching a scalar variable. When this happens, instead of rewriting the op tree and cleaning up the dangling pointers, it&#39;s easier just to replace the redundant operation with the null op. Originally, the tree would have looked like this:</p>

<pre><code class="plaintext">10          SVOP (0x816b4f0) rv2sv [15]
11              SVOP (0x816dcf0) gv  GV (0x80fa460) *a</code></pre>

<p>That is, fetch the <code>a</code> entry from the main symbol table, and then look at the scalar component of it: <code>gvsv</code> (<code>pp_gvsv</code> in <i>pp_hot.c</i>) happens to do both these things.</p>

<p>The right hand side, starting at line 5 is similar to what we&#39;ve just seen: we have the <code>add</code> op (<code>pp_add</code>, also in <i>pp_hot.c</i>) add together two <code>gvsv</code>s.</p>

<p>Now, what&#39;s this about?</p>

<pre><code class="plaintext">1  LISTOP (0x8179888) leave
2      OP (0x81798b0) enter
3      COP (0x8179850) nextstate</code></pre>

<p><code>enter</code> and <code>leave</code> are scoping ops, and their job is to perform any housekeeping every time you enter and leave a block: lexical variables are tidied up, unreferenced variables are destroyed, and so on. Every program will have those first three lines: <code>leave</code> is a list, and its children are all the statements in the block. Statements are delimited by <code>nextstate</code>, so a block is a collection of <code>nextstate</code> ops, with the ops to be performed for each statement being the children of <code>nextstate</code>. <code>enter</code> is a single op which functions as a marker.</p>

<p>That&#39;s how Perl parsed the program, from top to bottom:</p>

<pre><code> Program
    |
Statement
    |
    =
   / \
  /   \
 $a   +
     / \
   $b   $c</code></pre>

<p>However, it&#39;s impossible to <b>perform</b> the operations in this order: you have to find the values of <code>$b</code> and <code>$c</code> before you add them together, for instance. So, the other thread that runs through the op tree is the execution order: each op has a field <code>op_next</code> which points to the next op to be run, so following these pointers tells us how perl executes the code. We can traverse the tree in this order using the <code>exec</code> option to <code>B::Terse</code>:</p>

<pre><code>% perl -MO=Terse,exec -e &#39;$a=$b+$c&#39;
1  OP (0x8179928) enter
2  COP (0x81798c8) nextstate
3  SVOP (0x81796c8) gvsv  GV (0x80fa4d4) *b
4  SVOP (0x8179798) gvsv  GV (0x80efeb0) *c
5  BINOP (0x8179878) add [1]
6  SVOP (0x816dd38) gvsv  GV (0x80fa468) *a
7  BINOP (0x81798a0) sassign
8  LISTOP (0x8179900) leave</code></pre>

<p>This probably makes more sense for a human: enter a block, start a statement. Get the values of <code>$b</code> and <code>$c</code>, and add them together. Find <code>$a</code>, and assign one to the other. Then leave.</p>

<p>The way Perl builds up these op trees in the parsing process can be unravelled by examining <i>toke.c</i>, the lexer, and <i>perly.y</i>, the YACC grammar. Let&#39;s look at the code that constructs the tree for <code>$a = $b + $c</code>.</p>

<p>First, we&#39;ll look at the <code>Perl_yylex</code> function in the lexer. We want to look for <code>case &#39;x&#39;</code>, where x is the first character of the operator. (Incidentally, when looking for the code that handles a keyword, you&#39;ll want to search for <code>KEY_foo</code> where &quot;foo&quot; is the keyword.) Here is the code that handles assignment (there are quite a few operators beginning with <code>=</code>, so most of it is omitted for brevity):</p>

<pre><code>1    case &#39;=&#39;:
2        s++;
         ... code that handles == =&gt; etc. and pod ...
3        pl_yylval.ival = 0;
4        OPERATOR(ASSIGNOP);</code></pre>

<p>We can see on line 4 that our token type is <code>ASSIGNOP</code> (<code>OPERATOR</code> is a macro, defined in <i>toke.c</i>, that returns the token type, among other things). And <code>+</code>:</p>

<pre><code>1     case &#39;+&#39;:
2         {
3             const char tmp = *s++;
              ... code for ++ ...
4             if (PL_expect == XOPERATOR) {
                  ...
5                 Aop(OP_ADD);
6             }
              ...
7         }</code></pre>

<p>Line 4 checks what type of token we are expecting. <code>Aop</code> returns a token. If you search for <code>Aop</code> elsewhere in <i>toke.c</i>, you will see that it returns an <code>ADDOP</code> token.</p>

<p>Now that we know the two token types we want to look for in the parser, let&#39;s take the piece of <i>perly.y</i> we need to construct the tree for <code>$a = $b + $c</code></p>

<pre><code>1 term    :   term ASSIGNOP term
2                { $$ = newASSIGNOP(OPf_STACKED, $1, $2, $3); }
3         |   term ADDOP term
4                { $$ = newBINOP($2, 0, scalar($1), scalar($3)); }</code></pre>

<p>If you&#39;re not used to reading BNF grammars, this is how it works: You&#39;re fed certain things by the tokeniser, which generally end up in upper case. <code>ADDOP</code> and <code>ASSIGNOP</code> are examples of &quot;terminal symbols&quot;, because you can&#39;t get any simpler than them.</p>

<p>The grammar, lines one and three of the snippet above, tells you how to build up more complex forms. These complex forms, &quot;non-terminal symbols&quot; are generally placed in lower case. <code>term</code> here is a non-terminal symbol, representing a single expression.</p>

<p>The grammar gives you the following rule: you can make the thing on the left of the colon if you see all the things on the right in sequence. This is called a &quot;reduction&quot;, and the aim of parsing is to completely reduce the input. There are several different ways you can perform a reduction, separated by vertical bars: so, <code>term</code> followed by <code>=</code> followed by <code>term</code> makes a <code>term</code>, and <code>term</code> followed by <code>+</code> followed by <code>term</code> can also make a <code>term</code>.</p>

<p>So, if you see two terms with an <code>=</code> or <code>+</code>, between them, you can turn them into a single expression. When you do this, you execute the code in the block on the next line: if you see <code>=</code>, you&#39;ll do the code in line 2. If you see <code>+</code>, you&#39;ll do the code in line 4. It&#39;s this code which contributes to the op tree.</p>

<pre><code>|   term ADDOP term
{ $$ = newBINOP($2, 0, scalar($1), scalar($3)); }</code></pre>

<p>What this does is creates a new binary op, and feeds it a number of variables. The variables refer to the tokens: <code>$1</code> is the first token in the input, <code>$2</code> the second, and so on - think regular expression backreferences. <code>$$</code> is the op returned from this reduction. So, we call <code>newBINOP</code> to create a new binary operator. The first parameter to <code>newBINOP</code>, a function in <i>op.c</i>, is the op type. It&#39;s an addition operator, so we want the type to be <code>ADDOP</code>. We could specify this directly, but it&#39;s right there as the second token in the input, so we use <code>$2</code>. The second parameter is the op&#39;s flags: 0 means &quot;nothing special&quot;. Then the things to add: the left and right hand side of our expression, in scalar context.</p>

<p>The functions that create ops, which have names like <code>newUNOP</code> and <code>newBINOP</code>, call a &quot;check&quot; function associated with each op type, before returning the op. The check functions can mangle the op as they see fit, and even replace it with an entirely new one. These functions are defined in <i>op.c</i>, and have a <code>Perl_ck_</code> prefix. You can find out which check function is used for a particular op type by looking in <i>regen/opcodes</i>. Take <code>OP_ADD</code>, for example. (<code>OP_ADD</code> is the token value from the <code>Aop(OP_ADD)</code> in <i>toke.c</i> which the parser passes to <code>newBINOP</code> as its first argument.) Here is the relevant line:</p>

<pre><code class="plaintext">add             addition (+)            ck_null         IfsT2   S S</code></pre>

<p>The check function in this case is <code>Perl_ck_null</code>, which does nothing. Let&#39;s look at a more interesting case:</p>

<pre><code class="plaintext">readline        &lt;HANDLE&gt;                ck_readline     t%      F?</code></pre>

<p>And here is the function from <i>op.c</i>:</p>

<pre><code> 1 OP *
 2 Perl_ck_readline(pTHX_ OP *o)
 3 {
 4     PERL_ARGS_ASSERT_CK_READLINE;
 5 
 6     if (o-&gt;op_flags &amp; OPf_KIDS) {
 7          OP *kid = cLISTOPo-&gt;op_first;
 8          if (kid-&gt;op_type == OP_RV2GV)
 9              kid-&gt;op_private |= OPpALLOW_FAKE;
10     }
11     else {
12         OP * const newop
13             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0,
14                                               PL_argvgv));
15         op_free(o);
16         return newop;
17     }
18     return o;
19 }</code></pre>

<p>One particularly interesting aspect is that if the op has no kids (i.e., <code>readline()</code> or <code>&lt;&gt;</code>) the op is freed and replaced with an entirely new one that references <code>*ARGV</code> (lines 12-16).</p>

<h1 id="STACKS"><a class="permalink" href="perlinterp.html#STACKS">#</a>STACKS</h1>

<p>When perl executes something like <code>addop</code>, how does it pass on its results to the next op? The answer is, through the use of stacks. Perl has a number of stacks to store things it&#39;s currently working on, and we&#39;ll look at the three most important ones here.</p>

<h2 id="Argument-stack"><a class="permalink" href="perlinterp.html#Argument-stack">#</a><a id="Argument"></a>Argument stack</h2>

<p>Arguments are passed to PP code and returned from PP code using the argument stack, <code>ST</code>. The typical way to handle arguments is to pop them off the stack, deal with them how you wish, and then push the result back onto the stack. This is how, for instance, the cosine operator works:</p>

<pre><code>NV value;
value = POPn;
value = Perl_cos(value);
XPUSHn(value);</code></pre>

<p>We&#39;ll see a more tricky example of this when we consider Perl&#39;s macros below. <code>POPn</code> gives you the NV (floating point value) of the top SV on the stack: the <code>$x</code> in <code>cos($x)</code>. Then we compute the cosine, and push the result back as an NV. The <code>X</code> in <code>XPUSHn</code> means that the stack should be extended if necessary - it can&#39;t be necessary here, because we know there&#39;s room for one more item on the stack, since we&#39;ve just removed one! The <code>XPUSH*</code> macros at least guarantee safety.</p>

<p>Alternatively, you can fiddle with the stack directly: <code>SP</code> gives you the first element in your portion of the stack, and <code>TOP*</code> gives you the top SV/IV/NV/etc. on the stack. So, for instance, to do unary negation of an integer:</p>

<pre><code>SETi(-TOPi);</code></pre>

<p>Just set the integer value of the top stack entry to its negation.</p>

<p>Argument stack manipulation in the core is exactly the same as it is in XSUBs - see <a href="perlxstut.html">perlxstut</a>, <a href="perlxs.html">perlxs</a> and <a href="perlguts.html">perlguts</a> for a longer description of the macros used in stack manipulation.</p>

<h2 id="Mark-stack"><a class="permalink" href="perlinterp.html#Mark-stack">#</a><a id="Mark"></a>Mark stack</h2>

<p>I say &quot;your portion of the stack&quot; above because PP code doesn&#39;t necessarily get the whole stack to itself: if your function calls another function, you&#39;ll only want to expose the arguments aimed for the called function, and not (necessarily) let it get at your own data. The way we do this is to have a &quot;virtual&quot; bottom-of-stack, exposed to each function. The mark stack keeps bookmarks to locations in the argument stack usable by each function. For instance, when dealing with a tied variable, (internally, something with &quot;P&quot; magic) Perl has to call methods for accesses to the tied variables. However, we need to separate the arguments exposed to the method to the argument exposed to the original function - the store or fetch or whatever it may be. Here&#39;s roughly how the tied <code>push</code> is implemented; see <code>av_push</code> in <i>av.c</i>:</p>

<pre><code>1	PUSHMARK(SP);
2	EXTEND(SP,2);
3	PUSHs(SvTIED_obj((SV*)av, mg));
4	PUSHs(val);
5	PUTBACK;
6	ENTER;
7	call_method(&quot;PUSH&quot;, G_SCALAR|G_DISCARD);
8	LEAVE;</code></pre>

<p>Let&#39;s examine the whole implementation, for practice:</p>

<pre><code>1	PUSHMARK(SP);</code></pre>

<p>Push the current state of the stack pointer onto the mark stack. This is so that when we&#39;ve finished adding items to the argument stack, Perl knows how many things we&#39;ve added recently.</p>

<pre><code>2	EXTEND(SP,2);
3	PUSHs(SvTIED_obj((SV*)av, mg));
4	PUSHs(val);</code></pre>

<p>We&#39;re going to add two more items onto the argument stack: when you have a tied array, the <code>PUSH</code> subroutine receives the object and the value to be pushed, and that&#39;s exactly what we have here - the tied object, retrieved with <code>SvTIED_obj</code>, and the value, the SV <code>val</code>.</p>

<pre><code>5	PUTBACK;</code></pre>

<p>Next we tell Perl to update the global stack pointer from our internal variable: <code>dSP</code> only gave us a local copy, not a reference to the global.</p>

<pre><code>6	ENTER;
7	call_method(&quot;PUSH&quot;, G_SCALAR|G_DISCARD);
8	LEAVE;</code></pre>

<p><code>ENTER</code> and <code>LEAVE</code> localise a block of code - they make sure that all variables are tidied up, everything that has been localised gets its previous value returned, and so on. Think of them as the <code>{</code> and <code>}</code> of a Perl block.</p>

<p>To actually do the magic method call, we have to call a subroutine in Perl space: <code>call_method</code> takes care of that, and it&#39;s described in <a href="perlcall.html">perlcall</a>. We call the <code>PUSH</code> method in scalar context, and we&#39;re going to discard its return value. The call_method() function removes the top element of the mark stack, so there is nothing for the caller to clean up.</p>

<h2 id="Save-stack"><a class="permalink" href="perlinterp.html#Save-stack">#</a><a id="Save"></a>Save stack</h2>

<p>C doesn&#39;t have a concept of local scope, so perl provides one. We&#39;ve seen that <code>ENTER</code> and <code>LEAVE</code> are used as scoping braces; the save stack implements the C equivalent of, for example:</p>

<pre><code>{
    local $foo = 42;
    ...
}</code></pre>

<p>See <a href="perlguts.html#Localizing-changes">&quot;Localizing changes&quot; in perlguts</a> for how to use the save stack.</p>

<h1 id="MILLIONS-OF-MACROS"><a class="permalink" href="perlinterp.html#MILLIONS-OF-MACROS">#</a><a id="MILLIONS"></a>MILLIONS OF MACROS</h1>

<p>One thing you&#39;ll notice about the Perl source is that it&#39;s full of macros. Some have called the pervasive use of macros the hardest thing to understand, others find it adds to clarity. Let&#39;s take an example, a stripped-down version the code which implements the addition operator:</p>

<pre><code> 1  PP(pp_add)
 2  {
 3      dSP; dATARGET;
 4      tryAMAGICbin_MG(add_amg, AMGf_assign|AMGf_numeric);
 5      {
 6        dPOPTOPnnrl_ul;
 7        SETn( left + right );
 8        RETURN;
 9      }
10  }</code></pre>

<p>Every line here (apart from the braces, of course) contains a macro. The first line sets up the function declaration as Perl expects for PP code; line 3 sets up variable declarations for the argument stack and the target, the return value of the operation. Line 4 tries to see if the addition operation is overloaded; if so, the appropriate subroutine is called.</p>

<p>Line 6 is another variable declaration - all variable declarations start with <code>d</code> - which pops from the top of the argument stack two NVs (hence <code>nn</code>) and puts them into the variables <code>right</code> and <code>left</code>, hence the <code>rl</code>. These are the two operands to the addition operator. Next, we call <code>SETn</code> to set the NV of the return value to the result of adding the two values. This done, we return - the <code>RETURN</code> macro makes sure that our return value is properly handled, and we pass the next operator to run back to the main run loop.</p>

<p>Most of these macros are explained in <a href="perlapi.html">perlapi</a>, and some of the more important ones are explained in <a href="perlxs.html">perlxs</a> as well. Pay special attention to <a href="perlguts.html#Background-and-PERL_IMPLICIT_CONTEXT">&quot;Background and PERL_IMPLICIT_CONTEXT&quot; in perlguts</a> for information on the <code>[pad]THX_?</code> macros.</p>

<h1 id="FURTHER-READING"><a class="permalink" href="perlinterp.html#FURTHER-READING">#</a><a id="FURTHER"></a>FURTHER READING</h1>

<p>For more information on the Perl internals, please see the documents listed at <a href="perl.html#Internals-and-C-Language-Interface">&quot;Internals and C Language Interface&quot; in perl</a>.</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
